package com.company.cloud.page.client;

import java.util.*;
import java.util.function.Function;

import javax.annotation.Resource;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.article.modules.api.response.ArticleReap;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.page.modules.api.models.WechatMomentsSearch4PageModel;
import com.company.cloud.page.modules.api.models.WechatMomentsSearchModel;
import com.company.cloud.page.modules.api.request.PageUserCardAddByCompanyRequest;
import com.company.cloud.page.modules.api.response.PageCardConfigResponse;
import com.company.cloud.page.modules.api.response.WechatMomentsResponse;
import com.company.cloud.page.modules.base.entity.PageCardConfigInfo;
import com.company.cloud.page.modules.base.service.PageCardConfigInfoService;
import com.company.cloud.page.modules.mgr.service.PageCardConfigMgrService;
import com.company.common.server.constant.IRelBusiType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.cloud.article.modules.api.service.ArticleClientService;
import com.company.cloud.behavior.modules.api.response.BehaviorSearchListParam;
import com.company.cloud.behavior.modules.api.response.ThumbsUpSearchModel;
import com.company.cloud.behavior.modules.api.service.BehaviorClientService;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.page.modules.api.models.RelModel;
import com.company.cloud.page.modules.api.models.WechatMomentsModel;
import com.company.cloud.page.modules.api.service.PageClientService;
import com.company.cloud.page.modules.base.entity.WechatMomentsInfo;
import com.company.cloud.page.modules.base.service.WechatMomentsInfoService;
import com.company.cloud.page.modules.cache.utils.MomentsConvertUtils;
import com.company.cloud.product.modules.api.response.Product;
import com.company.cloud.product.modules.api.service.ProductRemoteService;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Service
public class PageClientServiceImpl implements PageClientService {

    @Autowired
    private WechatMomentsInfoService wechatMomentsInfoService;
    @Resource
    private ArticleClientService articleClientService;
    //    @Resource
//    private TrainClientService trainClientService;
//    @Resource
//    private PosterClientService posterClientService;
    @Resource
    private ProductRemoteService productRemoteService;
    @Resource
    private BehaviorClientService behaviorClientService;
    @Autowired
    private PageCardConfigInfoService pageCardConfigInfoService;
    @Autowired
    private PageCardConfigMgrService pageCardConfigMgrService;

    @Override
    public BaseClientResult<List<WechatMomentsModel>> getWechatMoments2List(WechatMomentsSearchModel param) {
        try {
            ValidatorUtils.validate(param);
            List<WechatMomentsInfo> list = wechatMomentsInfoService.list(
                    new QueryWrapper<WechatMomentsInfo>()
                            .eq("user_id", param.getUserId())
                            .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
                            .last("limit 0," + param.getTop())
                            .orderByDesc("cdt")
            );
            return BaseClientResult.success(this.getResult(list));
        } catch (Exception e) {
            return BaseClientResult.error(e);
        }
    }


    private List<WechatMomentsModel> getResult(List<WechatMomentsInfo> list) {
        List<WechatMomentsModel> result = new ArrayList<WechatMomentsModel>();
        if (CollectionUtils.isEmpty(list)) {
            return result;
        }
        // 获取点赞和评论信息参数
        BehaviorSearchListParam bParam = new BehaviorSearchListParam();
        bParam.setObjType(IRelBusiType.CMS_Moment);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUserNoValidate();
        if (userInfo != null && CheckUtils.hasInt(userInfo.getId())) {
            bParam.setUserId(userInfo.getId());
        } else {
            bParam.setUserId(0);
        }
        List<String> objNo = new ArrayList<String>();
        list.forEach(item -> {
            WechatMomentsModel model = MomentsConvertUtils.getWechatMomentsModel(item);
            // 设定各个关联业务的对象
            result.add(getRelInfo(model));
            objNo.add(Integer.toString(item.getId()));
        });
        bParam.setObjNo(objNo);
        List<ThumbsUpSearchModel> thumbsUpList = behaviorClientService.getThumbsUpList(bParam).getData();
        List<Integer> commentList = behaviorClientService.getCommentList(bParam).getData();
        for (int i = 0; i < result.size(); i++) {
            result.get(i).setThumbsUp(thumbsUpList.get(i));
            result.get(i).setCommentCount(commentList.get(i));
        }
        return result;
    }


    @Override
    public BaseClientResult<WechatMomentsResponse> getWechatMoments2Page(WechatMomentsSearch4PageModel param) {
        try {
            IPage<WechatMomentsInfo> page = wechatMomentsInfoService.page(new Page<>(param.getPage(), param.getRows()),
                    new QueryWrapper<WechatMomentsInfo>()
                            .eq("user_id", param.getUserId())
                            .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
                            .orderByDesc("cdt")
            );

            IPage<WechatMomentsModel> data = page.convert(new Function<WechatMomentsInfo, WechatMomentsModel>() {
                @Override
                public WechatMomentsModel apply(WechatMomentsInfo entity) {
                    return MomentsConvertUtils.getWechatMomentsModel(entity);
                }
            });

            List<WechatMomentsModel> result = this.getResult(page.getRecords());
            data.setRecords(result);
            return BaseClientResult.success(new WechatMomentsResponse(data));
        } catch (Exception e) {
            return BaseClientResult.error(e);
        }

    }

    @Override
    public BaseClientResult<PageCardConfigResponse> getPageCardConfig(String pageNo) {
        try {
            PageCardConfigInfo entity = pageCardConfigInfoService.getById(pageNo);
            if (entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
                return null;
            }
            PageCardConfigResponse data = new PageCardConfigResponse();
            BeanUtil.copyProperties(entity, data);
            return BaseClientResult.success(data);
        } catch (Exception e) {
            return BaseClientResult.error(e);
        }
    }

    @Override
    public BaseClientResult<Map<String, PageCardConfigResponse>> getPageCardConfigMap(Set<String> pageNo) {
        try {
            Map<String, PageCardConfigResponse> data = new HashMap<>();
            List<PageCardConfigInfo> list = pageCardConfigInfoService.listByIds(pageNo);
            if (!CollectionUtils.isEmpty(list)) {
                list.forEach(entity -> {
                    if (entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {

                    } else {
                        PageCardConfigResponse pageCardConfigResponse = new PageCardConfigResponse();
                        BeanUtil.copyProperties(entity, pageCardConfigResponse);
                        data.put(pageCardConfigResponse.getPageNo(), pageCardConfigResponse);
                    }
                });
            }
            return BaseClientResult.success(data);
        } catch (Exception e) {
            return BaseClientResult.error(e);
        }
    }

    @Override
    public BaseClientResult<PageCardConfigResponse> addUserPageCardByCompany(PageUserCardAddByCompanyRequest request) {
        try {
            LoginSimpleUserInfo userInfo = new LoginSimpleUserInfo();
            userInfo.setId(request.getOpUserId());
            userInfo.setIp(request.getOpIp());
            PageCardConfigInfo entity = pageCardConfigMgrService.addUserPageCardByCompany(request.getUserId(), request.getCompanyNo(), userInfo);
            PageCardConfigResponse data = new PageCardConfigResponse();
            if (entity != null) {
                BeanUtil.copyProperties(entity, data);
            }
            return BaseClientResult.success(data);
        } catch (Exception e) {
            return BaseClientResult.error(e);
        }
    }

    private WechatMomentsModel getRelInfo(WechatMomentsModel model) {
        RelModel relModel = new RelModel();
        if (IRelBusiType.CMS_Article.equals(model.getRelIdType())) {
            ArticleReap rel = articleClientService.getCompanyArticleByNo(model.getRelId()).getData();
            if (rel != null && StringUtils.hasText(rel.getArticleNo())) {
                relModel.setRelIdType(model.getRelIdType());
                relModel.setRelId(model.getRelId());
                relModel.setTitle(rel.getTitle());
                relModel.setThumbnail(rel.getThumbnail());
                model.setRelModel(relModel);
            }
        }
        if (IRelBusiType.CMS_Course.equals(model.getRelIdType())) {
//            CourseClientModel rel = trainClientService.getCourseClientModel(model.getRelId()).getData();
//            if (rel != null && StringUtils.hasText(rel.getCourseRelNo())) {
//                relModel.setRelIdType(model.getRelIdType());
//                relModel.setRelId(model.getRelId());
//                relModel.setTitle(rel.getTitle());
//                relModel.setThumbnail(rel.getPicture());
//                model.setRelModel(relModel);
//            }
        }
        if (IRelBusiType.CMS_Poster.equals(model.getRelIdType())) {
//            PosterCompanyModel4Client rel = posterClientService.getPosterCompanyByCache(model.getRelId()).getData();
//            if (rel != null && StringUtils.hasText(rel.getPosterNo())) {
//                relModel.setRelIdType(model.getRelIdType());
//                relModel.setRelId(model.getRelId());
//                relModel.setTitle(rel.getTitle());
//                relModel.setThumbnail(rel.getThumbnailImg());
//                model.setRelModel(relModel);
//            }
        }
        if (IRelBusiType.PRD_Product.equals(model.getRelIdType())) {
            BaseClientResult<Product> rel = productRemoteService.getProductByDbById(model.getRelId());
            if (BaseReturnEnum.SUCCESS.getCode().equals(rel.getCode()) && null != rel.getData()) {
                relModel.setRelIdType(model.getRelIdType());
                relModel.setRelId(model.getRelId());
                relModel.setTitle(rel.getData().getName());
                relModel.setThumbnail(rel.getData().getImage());
                model.setRelModel(relModel);
            }
        }
        return model;
    }
}
